package bms;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class BookManager implements Function {
    private List<Book> bookList;
    private Scanner scanner;
    String filePath = "C:/mydownload/ideajavaweb/mybook2.txt";

    public BookManager() {
        bookList = new ArrayList<>();
        scanner = new Scanner(System.in);
    }

    @Override
    public void addBook() {

    }

    @Override
    public void deleteBook() {

    }

    public void showMenu() {
        Scanner scanner = new Scanner(System.in);
        boolean exit = false;
        BookManager start = new BookManager();
        bookList = start.readfile(filePath);//程序启动时就读文件
        print(bookList);
        rollback:
        while (!exit) {
            System.out.println("请选择操作：");
            System.out.println("1. 添加 Book");
            System.out.println("2. 打印 Book");
            System.out.println("3. 删除 Book");
            System.out.println("4. 查询 Book");
//            System.out.println("5. 保存文件");
//            System.out.println("5. 读文件");
            System.out.println("5. 退出");

            int option = scanner.nextInt();
            switch (option) {
                case 1:
                    addBook(scanner);
                    savefile(bookList, filePath);
                    break;
                case 2:
                    print(bookList);
                    break;
                case 3:

                    deleteBook(scanner, bookList);
                    savefile(bookList, filePath);
                    break;
                case 4:
                    readfile(filePath);
                    queryBook(scanner);
                    break;
//                case 5:
//                    savefile(bookList, filePath);
//                case 5:
//                    readfile(filePath);
                case 5:
                    exit = true;
                    break;
                default:
                    System.out.println("无效选项，请重新输入");
                    break;

            }
        }
    }

    @Override
    public void queryBook() {

    }

    public void addBook(Scanner scanner) {
        System.out.println("请输入 Book 信息:");
        System.out.print("名称：");
        String name = scanner.next();
        System.out.print("出版社：");
        String publisher = scanner.next();
        System.out.print("作者：");
        String author = scanner.next();
        System.out.print("ISBN：");
        String isbn = scanner.next();

        Book book = new Book(name, publisher, author, isbn);
        bookList.add(book);
//        System.out.println("添加 Book 成功：" + book.toString());

    }

    public String pri(List<Book> books, int i) {

        System.out.println("书名:" + books.get(i).getName());
        System.out.println("出版社:" + books.get(i).getPublisher());
        System.out.println("作者:" + books.get(i).getAuthor());
        System.out.println("ISBN:" + books.get(i).getISBN());
        String information = ("书名" + books.get(i).getName());
        return information;
    }

    public void print(List<Book> books) {
        int num = books.size();
        for (int i = 0; i < num; i++) {
            pri(books, i);
        }
    }

    public void deleteBook(Scanner scanner, List<Book> list) {
        System.out.println("请输入要删除的 Book 的 ISBN：");
        String isbn = scanner.next();
        Book bookToRemove = null;
        for (Book bookd : list) {
            if (bookd.getISBN().equals(isbn)) {
                bookToRemove = bookd;
                break;
            }
        }
        if (bookToRemove != null) {
            list.remove(bookToRemove);
            System.out.println("删除 Book 成功：" + bookToRemove);
        } else {
            System.out.println("没有找到指定的 Book：" + isbn);
        }

    }

    public void queryBook(Scanner scanner) {
        System.out.println("请输入要查询的 Book 的 ISBN：");
        String isbn = scanner.next();
        Book queryBook = null;
        for (Book book : bookList) {
            if (book.getISBN().equals(isbn)) {
                queryBook = book;
                break;
            }
        }

        if (queryBook != null) {
            System.out.println("查询到的 Book 信息：" + queryBook.toString());
        } else {
            System.out.println("没有找到指定的 Book：" + isbn);
        }
    }

    public void savefile(List<Book> books, String filePath) {
        FileWriter fw = null;
        try {

            File file = new File("C:/mydownload/ideajavaweb/mybook2.txt");
            //if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            //true = append file
            FileWriter fileWritter = new FileWriter(filePath);
//            fileWritter.write(books);

            for (int i = 0; i < bookList.size(); i++) {
                Book book = bookList.get(i);
                fileWritter.write(book.getName() + "," + book.getPublisher() + "," + book.getAuthor() + "," + book.getISBN() + "\n");
            }
            fileWritter.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
//            File file = new File(filePath);
//            if (!file.exists()) {
//                file.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
//            }
//            FileOutputStream fos = new FileOutputStream(file, true);
//            OutputStreamWriter osw = new OutputStreamWriter(fos);
//            BufferedWriter bw = new BufferedWriter(osw);
//            for (Book b : books
//            ) {
//                bw.write(b.getName() + b.getPublisher() + b.getAuthor() + b.getISBN());
//            }
//            bw.newLine();
//            bw.flush();
//            bw.close();
//            osw.close();
//            fos.close();
//        } catch (FileNotFoundException e1) {
//            e1.printStackTrace();
//        } catch (IOException e2) {
//            e2.printStackTrace();
//        } finally {
//            try {
//                if (fw != null)
//                    fw.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

    }


    public List<Book> readfile(String pathName) {
        List<Book> list = new ArrayList<>();
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(pathName)))) {
            int len = 0;
            byte[] buffer = new byte[512];
            String message = "";
            //获取所有字符
            while ((len = bis.read(buffer)) != -1) {
                message = new String(buffer, 0, len, "GBK"); //为防止中文乱码，设置字符集为GBK
            }
            String[] arr = message.split("\n"); //将获取的字符按行分割
            //获取每一行的数据并封装成lineinformation对象

            for (int i = 0; i < arr.length; i++) {
                String[] line = arr[i].split(",");


                Book lineinformation = new Book(line);
                list.add(lineinformation);
            }
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

}